<template>
  <div class="dataBase class-model">
    <ContentWrap>
      <el-form :model="formOptions" ref="formRef">
        <el-row>
          <el-col :span="7" class="pr-5">
            <el-form-item label="模型名称" prop="name"
              ><ns-input
                v-model="formOptions.name"
                clearable
                placeholder="请输入模型名称"
                maxlength="50"
            /></el-form-item>
          </el-col>
          <el-col :span="7" class="pr-5" v-if="props.onlyShow">
            <el-form-item label="状态" prop="isAttach">
              <el-select v-model="formOptions.isAttach" placeholder="请选择状态" clearable>
                <el-option :value="true" label="开启" key="true" />
                <el-option :value="false" label="关闭" key="false" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" class="text-right">
            <el-button
              type="primary"
              @click="search"
              plain
              v-hasPermi="['system:modelManage-ClassModel:search']"
              >搜索</el-button
            >
            <el-button @click="reset" plain>重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </ContentWrap>
    <ContentWrap>
      <el-form-item v-if="!props.onlyShow">
        <el-button
          @click="addModel"
          type="primary"
          v-hasPermi="['system:modelManage-ClassModel:create']"
          >新增</el-button
        >
        <el-button
          @click="batchDelete"
          type="danger"
          :disabled="ids.length === 0"
          v-hasPermi="['system:modelManage-ClassModel:batchDelete']"
          >删除</el-button
        >
      </el-form-item>
      <AsyncTable
        :fetchData="fetchData"
        v-bind="tableInfo"
        ref="tableRef"
        @selection-change="getId"
      />
    </ContentWrap>
    <Dialog
      v-model="adoptDialog"
      :title="dialogType === 'create' ? '新增模型' : '编辑模型'"
      width="30%"
      close-on-click-modal
      destroy-on-close
    >
      <el-form
        label-suffix="："
        label-width="100px"
        :rules="adoptRefRules"
        :model="adoptValue"
        ref="adoptRef"
        :maxlength="50"
      >
        <el-form-item prop="name" label="模型名称" placeholder="请输入模型名称">
          <ns-input v-model="adoptValue.name" placeholder="请输入模型名称" clearable />
        </el-form-item>
        <el-form-item prop="comment" label="备注">
          <ns-input
            type="textarea"
            v-model.trim="adoptValue.describe"
            :rows="6"
            :maxlength="150"
            placeholder="请输入模型备注"
            @input="adoptValue.describe = adoptValue.describe.replace(/\s+/g, '')"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="adoptDialog = false">取消</el-button>
          <el-button type="primary" @click="create">确定</el-button>
        </span>
      </template>
    </Dialog>
  </div>
</template>

<script setup lang="tsx">
import * as apiModelManage from '@/api/machineModel/modelManage'
import * as apiClassModel from '@/api/machineModel/classModel'
import { useRouter } from 'vue-router'
const formRef = ref()
const tableRef = ref()
const adoptDialog = ref(false)
const router = useRouter()
const adoptRef = ref()
const ids = ref([])
const dialogType = ref('')
const { proxy } = getCurrentInstance()
const adoptRefRules = reactive({
  name: [{ required: true, message: '请输入模型名称', trigger: 'blur' }]
})
const adoptValue = ref({
  name: '',
  describe: '',
  id: '',
  status: 1
})
const formOptions = reactive({
  name: '',
  isAttach: null
})
const props = defineProps({
  id: {
    type: String,
    default: ''
  },
  onlyShow: {
    type: Boolean,
    default: false
  }
})
const tableInfo = reactive({
  columns: [
    {
      hide: props.onlyShow,
      type: 'selection',
      width: 60
    },
    {
      prop: 'name',
      label: '模型名称'
    },
    {
      hide: !props.onlyShow,
      prop: 'moduleVersion',
      label: '模型版本'
    },
    {
      label: props.onlyShow ? '备注' : '模型描述',
      render: ({ row }) => {
        return <> {row.describe || '--'} </>
      }
    },
    {
      hide: props.onlyShow,
      prop: 'moduleVersion',
      label: '启用版本'
    },
    {
      label: props.onlyShow ? '启用状态' : '是否启用',
      render: ({ row }) => {
        return props.onlyShow ? (
          <el-switch
            onChange={(val) => changeState(row, val)}
            v-model={row.attach}
            active-color="#409EFF"
            inactive-color="#ff4949"
          />
        ) : (
          <el-switch
            onChange={(val) => onToOffLine(row, val)}
            active-value={1}
            inactive-value={0}
            v-model={row.status}
            active-color="#409EFF"
            inactive-color="#ff4949"
          />
        )
      }
    },
    {
      prop: 'createTime',
      label: '创建时间'
    },
    {
      width: '180px',
      hide: props.onlyShow,
      label: '操作',
      render: ({ row }) => {
        return (
          <>
            <el-button
              type="primary"
              link
              size="small"
              onclick={() => {
                detail(row)
              }}
              v-hasPermi={[['system:odelManage-ClassModel:detail']]}
            >
              查看详情
            </el-button>{' '}
            <el-button
              type="primary"
              link
              size="small"
              onclick={() => {
                edit(row)
              }}
              v-hasPermi={[['system:odelManage-ClassModel:edit']]}
            >
              编辑
            </el-button>
            <ns-button
              confirm
              type="danger"
              link
              size="small"
              style="margin-left: 5px"
              onClick={() => {
                del(row)
              }}
              v-hasPermi={[['system:odelManage-ClassModel:singleDelete']]}
            >
              删除
            </ns-button>
          </>
        )
      }
    }
  ],
  data: []
})
const search = () => {
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}
const reset = () => {
  formRef.value.resetFields()
  search()
}
const create = async () => {
  const v = await adoptRef.value.validate()
  if (v) {
    const { code } =
      dialogType.value === 'create'
        ? await apiModelManage.createModelManage(adoptValue.value)
        : await apiModelManage.editModelManage(adoptValue.value)
    code === 200 && ElMessage.success(dialogType.value === 'create' ? '新增成功' : '编辑成功')
    code === 200 && search()
    code === 200 && (adoptDialog.value = false)
  }
}
const edit = (row) => {
  dialogType.value = 'edit'
  adoptDialog.value = true
  adoptValue.value = {
    name: row.name,
    describe: row.describe,
    id: row.id,
    status: row.status
  }
}
const fetchData = async ({ page, pageSize }) => {
  const { data, count } = props.onlyShow
    ? await apiClassModel.classModelList({
        page,
        pageSize,
        dataStandardId: props.id,
        name: formOptions.name,
        isAttach: formOptions.isAttach
      })
    : await apiModelManage.modelManageList({
        page,
        pageSize,
        name: formOptions.name
      })
  return { data, count }
}
const getId = (val) => {
  ids.value = []
  val.map((item) => ids.value.push(item.id))
}
const changeState = (row, status) => {
  if (status) {
    apiClassModel.addClassModel({ dataStandardId: props.id, moduleId: row.id }).then(({ code }) => {
      code === 200 && ElMessage.success('修改成功')
      code === 200 && search()
    })
  } else {
    apiClassModel
      .cancleClassModel({ dataStandardId: props.id, moduleId: row.id })
      .then(({ code }) => {
        code === 200 && ElMessage.success('修改成功')
        code === 200 && search()
      })
  }
}
const onToOffLine = (row, status) => {
  if (status == 1 || status == 0) {
    apiModelManage.editModelManage({ ...row, status }).then(({ code }) => {
      code === 200 && ElMessage.success(status === 1 ? '上线成功' : '下线成功')
      code === 200 && search()
    })
  }
}
const del = (row) => {
  apiModelManage
    .delModelManage({
      idList: [row.id],
      allSelect: false
    })
    .then(({ code }) => {
      code === 200 && ElMessage.success('删除成功')
      code === 200 && search()
    })
}
const batchDelete = () => {
  proxy.$modal.confirm(`确定要删除所选数据吗？`).then(() => {
    apiModelManage
      .delModelManage({
        idList: ids.value,
        allSelect: false
      })
      .then(({ code }) => {
        code === 200 && ElMessage.success('删除成功')
        code === 200 && search()
      })
  })
}
const addModel = () => {
  dialogType.value = 'create'
  adoptDialog.value = true
  adoptValue.value = {
    name: '',
    describe: '',
    status: 1
  }
}
const detail = (row) => {
  router.push({
    path: '/system/modelDetail',
    query: { id: row.id }
  })
}
</script>

<style lang="scss" scoped>
.class-model {
  .el-select {
    width: 100%;
  }
}
</style>
